<template>
  <el-card shadow="hover" class="feedback-card">
    <div class="header">
      <h2>疫苗反馈管理</h2>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索医生编号或疫苗编号"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch" type="primary">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
        </template>
      </el-input>

      <el-radio-group
        v-model="timeRange"
        @change="handleTimeRangeChange"
        style="margin-left: 20px"
      >
        <el-radio-button label="7days">近7日</el-radio-button>
        <el-radio-button label="30days">近30日</el-radio-button>
        <el-radio-button label="all">全部</el-radio-button>
      </el-radio-group>

      <el-button type="primary" @click="exportExcel" style="margin-left: 20px">
        导出为 Excel
      </el-button>
    </div>

    <el-table
      :data="feedbacks"
      style="width: 100%"
      :loading="loading"
      border
      stripe
    >
      <el-table-column prop="vaccineNumbering" label="疫苗编号" />
      <el-table-column prop="doctorId" label="医生编号" />
      <el-table-column
        prop="feedbackTime"
        label="反馈时间"
        width="180"
        :formatter="formatDate"
      />
      <el-table-column
        prop="feedbackText"
        label="反馈内容"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="link" size="small" @click="viewDetail(scope.row)">
            查看
          </el-button>
          <el-button
            type="link"
            size="small"
            style="color: red"
            @click="deleteFeedback(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      background
      style="margin-top: 20px; text-align: right"
      @current-change="fetchFeedbacks"
      @size-change="handleSizeChange"
    />

    <el-dialog
      title="反馈详情"
      v-model:visible="detailDialogVisible"
      width="40%"
    >
      <p><strong>疫苗编号：</strong>{{ selectedFeedback.vaccineNumbering }}</p>
      <p><strong>医生编号：</strong>{{ selectedFeedback.doctorId }}</p>
      <p><strong>反馈时间：</strong>{{ formatDate(selectedFeedback) }}</p>
      <p><strong>反馈内容：</strong></p>
      <p style="white-space: pre-wrap">{{ selectedFeedback.feedbackText }}</p>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const timeRange = ref('7days')
const searchKeyword = ref('')
const feedbacks = ref([])
const total = ref(0)
const loading = ref(false)

const currentPage = ref(1)
const pageSize = ref(5)

const detailDialogVisible = ref(false)
const selectedFeedback = ref({})

function formatDate(row) {
  const dateStr = row?.feedbackTime
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const yyyy = date.getFullYear()
  const MM = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  return `${yyyy}--${MM}--${dd}`
}

async function fetchFeedbacks() {
  loading.value = true
  try {
    const res = await axios.get('http://127.0.0.1:8181/vaccineFeedback', {
      params: {
        timeRange: timeRange.value,
        search: searchKeyword.value.trim(),
        pageNum: currentPage.value,
        pageSize: pageSize.value,
      },
    })
    if (res.data.code === 0) {
      feedbacks.value = res.data.data.data
      total.value = res.data.data.total
    } else {
      ElMessage.error('获取反馈列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  } finally {
    loading.value = false
  }
}

function handleTimeRangeChange() {
  currentPage.value = 1
  fetchFeedbacks()
}

function handleSizeChange(newSize) {
  pageSize.value = newSize
  currentPage.value = 1
  fetchFeedbacks()
}

function handleSearch() {
  currentPage.value = 1
  fetchFeedbacks()
}

function viewDetail(row) {
  selectedFeedback.value = row
  detailDialogVisible.value = true
}

async function deleteFeedback(id) {
  try {
    await ElMessageBox.confirm('确定删除该反馈吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const res = await axios.delete(
      `http://127.0.0.1:8181/vaccineFeedback/${id}`
    )
    if (res.data.code === 0) {
      ElMessage.success('删除成功')
      fetchFeedbacks()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('请求失败：' + (error.message || error))
    }
  }
}

/** 导出当前条件反馈为 Excel */
async function exportExcel() {
  try {
    const res = await axios.get(
      'http://127.0.0.1:8181/vaccineFeedback/export',
      {
        params: {
          timeRange: timeRange.value,
          search: searchKeyword.value.trim(),
        },
        responseType: 'blob', // 重要，文件流
      }
    )

    // 处理文件下载
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `疫苗反馈_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    link.remove()
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

onMounted(() => {
  fetchFeedbacks()
})
</script>

<style scoped>
.feedback-card {
  margin: 20px;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
</style>
